<template>
  <div>
    <div class="search">
      <input v-model="keyWord" type="text" placeholder="请输入地址或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyWord">
      <ul>
        <li class="border-top"
            v-for="item of list"
            :key="item.id"
            @click="handleCityClick(item.name)"
        >
          {{item.name}}
        </li>
        <li class="border-top" v-show="hasNoData">未找到匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyWord: '',
      timer: null,
      list: []
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyWord () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWord) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((val) => {
            if (val.name.indexOf(this.keyWord) > -1 ||
                val.spell.indexOf(this.keyWord) > -1
            ) {
              result.push(val)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.search {
  width: 100%;
  height: 0.72rem;
  background: $bgColor;
  padding: 0 0.1rem;
  box-sizing: border-box;

  input {
    width: 100%;
    height: 0.62rem;
    line-height: 0.62rem;
    text-align: center;
    border-radius: 0.09rem;
    color: #666;
    padding: 0 0.1rem;
    box-sizing: border-box;
  }
}
.search-content{
  position absolute
  top 1.58rem
  left 0
  right 0
  bottom 0
  overflow hidden
  background #eee
  z-index 1
  li{
    line-height .62rem
    background #fff
    padding-left .2rem
  }
}
</style>
